//
//  YNIMTool.m
//  YNIMFramework
//
//  Created by 黄旭 on 2021/7/19.
//

#import "YNIMTool.h"
#import <UIKit/UIKit.h>
#import <CommonCrypto/CommonCrypto.h>

@implementation YNIMTool
//object转json
+ (NSString *)jsonStringWithObject:(id)obj
{
    if ([self isEmptyObject:obj]) {
        return @"";
    }
    if ([obj isKindOfClass:[NSString class]]) {
        NSString*objStr=[NSString stringWithFormat:@"\"%@\"",obj];
        return objStr;
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    if ([self isEmptyString:jsonString]) {
        jsonString=@"";
    }
    return jsonString;
}
///获取uuid
+ (NSString *)identifierForVendor1
{
    return [NSUUID UUID].UUIDString;
}
//获取GUID
+(NSString *)getGUID
{
    CFUUIDRef    uuidObj = CFUUIDCreate(nil);//create a new UUID
    
    NSString   *uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(nil, uuidObj);
    
    CFRelease(uuidObj);
    
    return uuidString ;
    
}
/**
 * DES加密
 * plaintText           明文，即是需要加密字符串
 * key                  密匙，服务器和客户端共同规定
 * iv                   向量，加密解密需相同
 * result               NSString加密字符串
**/
+ (NSString *)encryptUseDES:(NSString *)plainText key:(NSString *)key iv:(NSString *)iv
{
    NSString *ciphertext = nil;
    NSData *encryptData = [plainText dataUsingEncoding:NSUTF8StringEncoding];

    NSInteger dataInLength;
    dataInLength = [encryptData length];

    unsigned char buffer[1024];
    memset(buffer, 0, 1024);
    size_t numBytesEncrypted = 0;

    CCCryptorStatus ccStatus;
    
    ccStatus = CCCrypt(kCCEncrypt,
                       kCCAlgorithmDES,
                       kCCOptionPKCS7Padding,
                       [key UTF8String],
                       kCCKeySizeDES,
                       [key UTF8String],
                       [encryptData bytes],
                       dataInLength,
                       buffer,
                       1024,
                       &numBytesEncrypted);
    
    if (ccStatus == kCCSuccess) {
        //debugLog(@"numBytesEncrypted__%zd",numBytesEncrypted);
        ciphertext = [self parseByte2HexString:buffer byteLength:numBytesEncrypted];
       
    }
    return ciphertext;
}

+ (NSString *)parseByte2HexString:(Byte *)bytes byteLength:(long)length
{
    NSMutableString *hexStr = [[NSMutableString alloc]init];
    int i = 0;
    if(bytes) {
        while (i < length) {
            NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];     //16进制数
            if([hexByte length]==1) {
                [hexStr appendFormat:@"0%@", hexByte];
            } else {
                [hexStr appendFormat:@"%@", hexByte];
            }
            i ++;
        }
    }
    return hexStr;
}

/**HX** 黄旭添加-判断字符串是否为空 **/
+(BOOL)isEmptyString:(NSString*)str{
    if (![str isKindOfClass:[NSString class]]) {
        return YES;
    }
    return str == NULL || str == nil || [@"" isEqualToString:str] || [str isKindOfClass:[NSNull class]];
}
/**HX** 黄旭添加-判断数组是否为空 **/
+(BOOL)isEmptyArray:(NSArray*)array{
    if (![array isKindOfClass:[NSArray class]]) {
        return YES;
    }
    return array == nil || [array isKindOfClass:[NSNull class]] || array.count == 0;
}
/**HX** 黄旭添加-判断字典是否为空 **/
+(BOOL)isEmptyDictionary:(NSDictionary*)dic{
    if (![dic isKindOfClass:[NSDictionary class]]) {
        return YES;
    }
    return dic == nil || [dic isKindOfClass:[NSNull class]] || dic.allKeys.count == 0;
}
/**HX** 黄旭添加-判断对象是否为空 **/
+(BOOL)isEmptyObject:(id)_object{
    return (_object == nil || [_object isKindOfClass:[NSNull class]] || ([_object respondsToSelector:@selector(length)] && [(NSData *)_object length] == 0) || ([_object respondsToSelector:@selector(count)] && [(NSArray *)_object count] == 0));
}
//json字符串转对象
+(id)getJsonObjectFromJsonString:(NSString *)str
{
    if ([self isEmptyString:str]) {
        return nil;
    }
    NSData *JSONData = [str dataUsingEncoding:NSUTF8StringEncoding];
    if ([self isEmptyObject:JSONData]) {
        return nil;
    }
    NSError *parseError1;
    id responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments error:&parseError1];
    /**HX** 如果解析出来的数据为空，检查下是否包含iOS现有框架不能解析的特殊符号格式 **/
    if (parseError1) {
        NSLog(@"json第一次解析错误:%@",parseError1);
        str = [str stringByReplacingOccurrencesOfString:@"    " withString:@""];//“TAB”(制表)键打出的那种四个空格
        str = [str stringByReplacingOccurrencesOfString:@"(\\\\)"
                                                         withString:@"\\\\\\\\" options:NSRegularExpressionSearch
                                                              range:NSMakeRange(0, [str length])];
        str = [str stringByReplacingOccurrencesOfString:@"(\r)"
                                                         withString:@"\\\\r" options:NSRegularExpressionSearch
                                                              range:NSMakeRange(0, [str length])];
        str = [str stringByReplacingOccurrencesOfString:@"(\n)"
                                                         withString:@"\\\\n" options:NSRegularExpressionSearch
                                                              range:NSMakeRange(0, [str length])];
        JSONData = [str dataUsingEncoding:NSUTF8StringEncoding];
        if ([self isEmptyObject:JSONData]) {
            return nil;
        }
        NSError *parseError2;
        responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments error:&parseError2];
        if (parseError2) {
            NSLog(@"json第二次解析错误:%@",parseError2);
            responseJSON=nil;
        }
    }
    return responseJSON;
}
//将nil转换为NSNull null，主要针对指针类型
+ (id)nilFilter:(id)value
{
    return value == nil ? [NSNull null] : value;
}
/**
 正则筛选出指定匹配的数组集合
 如：[/@张三][/001]表情符号等
 @param text 目标字符串
 @param rexStr 正则表达式
 @return 结果
 */
+(NSArray<NSTextCheckingResult *> *)findAllMatchedText:(NSString *)text rexStr:(NSString*)rexStr
{
    if([self isEmptyString:text])
    {
        return nil;
    }
    NSString *string = text;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:rexStr options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *matches = [regex matchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, [string length])];
    return matches;
}
//获取当前时间
+(NSString *)dateStringFromCurrentDate
{
    NSDateFormatter *dataFormatter = [[NSDateFormatter alloc] init];
    [dataFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSString *currentDataStr = [dataFormatter stringFromDate:[NSDate date]];
    return currentDataStr;
}
/**
 正则匹配字符串
 
 @param str 目标字符
 @param regularStr 正则字符
 @return 结果
 */
+ (NSTextCheckingResult*)regularMatchingTheString:(NSString*)str regularString:(NSString*)regularStr{
    if ([self isEmptyString:str]) str=@"";
    if ([self isEmptyString:regularStr]) regularStr=@"";
    
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regularStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSTextCheckingResult *result = [regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
    return result;
}
///imId兼容转化为平台userId
+(NSString*)getUseridFormImId:(NSString*)imId{
    if (imId == nil) {
        return nil;
    }
    NSArray*strArra=[imId componentsSeparatedByString:@"_"];
    if (strArra != nil && strArra.count==2) {
        return strArra.firstObject;
    }else{
        return imId;
    }
}
@end
